/*
Copyright © 2024 NAME HERE <EMAIL ADDRESS>
*/
package cmd

import (
	"bytes"
	"fmt"
	"log"
	"net"
	"time"

	"github.com/spf13/cobra"
)

func checkWater(v string) bool {
	push, err := net.Dial("tcp", fmt.Sprintf("%v:%v", v, REMOTE_PUSH))
	if err != nil {
		log.Println(err)
		return false
	}
	// push 端
	push.Write([]byte(ACCESS_POLICY))          // 访问验证
	push.Write([]byte(ACCESS_TRANSFER_POLICY)) // 策略验证
	push.Write([]byte(ACCESS_POLICY))          // 检查用
	push.Close()

	time.Sleep(100 * time.Millisecond)

	pull, err := net.Dial("tcp", fmt.Sprintf("%v:%v", v, REMOTE_PULL))
	if err != nil {
		log.Println(err)
		return false
	}
	// pull 端
	pull.Write([]byte(ACCESS_POLICY))          // 访问验证
	pull.Write([]byte(ACCESS_TRANSFER_POLICY)) // 策略验证

	var buffer = make([]byte, len(ACCESS_POLICY)) // 检查用
	_, err = pull.Read(buffer)                    // 检查值
	if err != nil {
		log.Println(err)
		return false
	}
	pull.Close()

	return bytes.Equal(buffer, []byte(ACCESS_POLICY))
}

// remoteAddCmd represents the remoteAdd command
var remoteAddCmd = &cobra.Command{
	Use:   "add",
	Short: "添加一个服务器",
	Long:  ``,
	Run: func(cmd *cobra.Command, args []string) {
		for _, v := range args {
			if checkWater(v) {
				log.Printf("服务器可用: %v\n", v)
			} else {
				log.Printf("服务器验证失败: %v\n", v)
			}
		}
	},
}

func init() {
	remoteCmd.AddCommand(remoteAddCmd)

	// Here you will define your flags and configuration settings.

	// Cobra supports Persistent Flags which will work for this command
	// and all subcommands, e.g.:
	// remoteAddCmd.PersistentFlags().String("foo", "", "A help for foo")

	// Cobra supports local flags which will only run when this command
	// is called directly, e.g.:
	// remoteAddCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle")
}
